package com.ThreadDemo;

/**
 * Created with IntelliJ IDEA.
 *
 * @Author: FENGYiMing
 * @Date: 2024/04/01/14:22
 * @Description:
 */
public class SellTicket {
    public static void main(String[] args) throws InterruptedException {
        //SellTicket01 sellTicket01 = new SellTicket01();
        //SellTicket01 sellTicket02 = new SellTicket01();
        //SellTicket01 sellTicket03 = new SellTicket01();
        //
        //sellTicket01.start();
        //sellTicket02.start();
        //sellTicket03.start();
        //Thread.sleep(2 * 1000);
        //sellTicket01.setLoop(false);
        SellTicket02 sellTicket02 = new SellTicket02();
        new Thread(sellTicket02).start();
        new Thread(sellTicket02).start();
        new Thread(sellTicket02).start();

    }
}

class SellTicket01 extends Thread {
    public static int ticketNum = 80;
    private boolean loop = true;

    public void sell() {
        synchronized (this) {

            if (ticketNum <= 0) {
                System.out.println("售票结束");
                loop = false;
                return;
            }
            try {
                Thread.sleep(100);
            } catch (InterruptedException e) {
                throw new RuntimeException(e);
            }
            System.out.println("正在售票" + (--ticketNum) + Thread.currentThread().getName());
        }


    }

    @Override
    public void run() {
        System.out.println("开始售票");
        while (loop) {
            sell();
        }

    }
}

class SellTicket02 implements Runnable {
    public static int ticketNum = 80;
    private boolean loop = true;

    public synchronized void sell() {

        if (ticketNum <= 0) {
            System.out.println("售票结束");
            loop = false;
            return;
        }
        try {
            Thread.sleep(100);
        } catch (InterruptedException e) {
            throw new RuntimeException(e);
        }
        System.out.println("正在售票" + (--ticketNum) + Thread.currentThread().getName());


    }

    @Override
    public void run() {
        System.out.println("开始售票");
        while (loop) {
            sell();
        }

    }
}
